package com.dqhl.community.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
/**
 * Created by LIENLIN on 2016/9/6.
 */
public class MyLetterView extends View{

	private Paint p;
	private static String[]letters={"A","B","C","D","E","F","G",
			"H","I","J","K","L","M","N",
			"O","P","Q","R","S","T","U",
			"V","W","X","Y","Z"};
	private OnTouchLetterListener listener;
	public MyLetterView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPaint();
	}

	public void setOnTouchLetterListener(OnTouchLetterListener listener)
	{
		this.listener=listener;
	}

	private void initPaint() {
		p=new Paint();
		int px=(int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_SP,//要转化的类型
				12, //该类型的尺寸值
				getResources().getDisplayMetrics()//屏幕密度
		);
		p.setTextSize(px);//sp--->px转化为的尺寸类型
//		p.setTypeface(Typeface.MONOSPACE);//设置字体

		/*p = new Paint();
		int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics());
		p.setTextSize(px);//12sp--->px
		//paint.setTypeface(Typeface.DEFAULT_BOLD);
*/	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		//控件的宽度
		int width =  getWidth();
		//控件的高度/27
		int height = getHeight()/27;

		for(int i=0;i<letters.length;i++){
			Rect bounds = new Rect();//画笔所画文字的宽高都存在bounds中
			p.getTextBounds(letters[i], 0, letters[i].length(), bounds );
			int letterWidth = bounds.width();//文字宽度
			int letterHeight = bounds.height();//文字高度
			float x = width/2-letterWidth/2;//控件的宽度/2 - 文字的宽度/2
			float y = height/2+letterHeight/2 + height*i;//控件的高度/27/2+文字的高度/2
			canvas.drawText(letters[i], x, y, p);
		}
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action=event.getAction();
		switch (action) {
			case MotionEvent.ACTION_DOWN:
			case MotionEvent.ACTION_MOVE:
				setBackgroundColor(Color.LTGRAY);//当按下和滑动时显示灰色

				float y2 = event.getY();
				int idx=(int) ((y2*letters.length)/getHeight());
				if (idx>=0&&idx<letters.length) {
					//调用接口的onTouchLetter()
					if (listener!=null) {
						listener.onTouchLetter(letters[idx]);
					}
				}



				break;
			default:
				setBackgroundColor(Color.TRANSPARENT);
				break;
		}


		return true;
	}
	public interface OnTouchLetterListener{
		void onTouchLetter(String letter);
	}

}
